// pages/login/login.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../api/index'),
    utils = require('../../utils/util');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        loading: false,
        toast: {
            visible: false,
            text: ''
        },
        loginOk: false,
        imageBaseUri: globalData.imageBaseUri,
        canIUseGetUserProfile: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (wx.getUserProfile) {
            console.log('111')
            this.setData({
                canIUseGetUserProfile: true
            })
        } else {
            console.log('222')
        }

        let pages = getCurrentPages(),
            page = pages[pages.length - 1],
            route = page ? page.route : '';
        console.log(route, 'route', page, 'page', pages, 'pages')
    },
    componentWillUnmount: function () {
        wx.setStorage({
            key: "isLoginPage",
            data: false
        })
    },
    onUnload: function () {
        // clearTimeout(timeout)
        wx.setStorage({
            key: "isLoginPage",
            data: false
        })
    },

    getUserProfile(e) {
        console.log(e, '获取用户信息2')
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
            desc: '用于下单购买商品', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res, '登录profile返回的res')
                let user = res.userInfo;
                let obj = {
                    nickname: user.nickName,
                    province: user.province,
                    sex: user.gender,
                    city: user.city,
                    country: user.country,
                    headimgurl: user.avatarUrl,
                    unionid: ''
                }

                wx.login({
                    success: res => {
                        console.log('wx.login', res)
                        this.setData({
                            loading: true
                        })
                        try {
                            api.base.wxOnLogin(Object.assign(obj, {
                                code: res.code
                            })).then(res => {
                                console.log(res, '登录结果')
                                let token = res.data.ResData.AccessToken || '',
                                    userinfo = res.data.ResData || {};

                                this.setData({
                                    userInfo: res.data.ResData,
                                    loading: false
                                })

                                //token
                                wx.setStorageSync('token', token);
                                // app.globalData.authToken = token;

                                //存放用户信息
                                wx.setStorageSync('userinfo', userinfo);
                                app.globalData.userInfo = userinfo;

                                // 存放sessionId
                                wx.setStorageSync('ssId', userinfo.WxSessionId);
                                app.globalData.ssId = userinfo.WxSessionId;
                            })
                            wx.setStorage({
                                key: "isLoginPage",
                                data: false
                            })
                            this.setData({
                                toast: {
                                    visible: true,
                                    text: '登录成功'
                                },
                                loginOk: true
                            })

                            if (this.data.loginOk) {
                                let t = setTimeout(function () {
                                    clearTimeout(t)
                                    wx.reLaunch({
                                        url: '/pages/index/index',
                                    })
                                }, 1500)
                            }

                        } catch (e) {
                            this.setData({
                                loading: false,
                                loginOk: false
                            })
                        }
                    }
                })
            }
        })
    },

    async getUserInfo(res) {
        console.log(res, '获取用户信息')
        if (res.detail) {
            let user = res.detail.userInfo;
            let obj = {
                nickname: user.nickName,
                province: user.province,
                sex: user.gender,
                city: user.city,
                country: user.country,
                headimgurl: user.avatarUrl,
                unionid: ''
            }

            wx.login({
                success: res => {
                    console.log('wx.login', res)
                    this.setData({
                        loading: true
                    })
                    try {
                        api.base.wxOnLogin(Object.assign(obj, {
                            code: res.code
                        })).then(res => {
                            console.log(res, '登录结果')
                            let token = res.data.ResData.AccessToken || '',
                                userinfo = res.data.ResData || {};

                            this.setData({
                                userInfo: res.data.ResData,
                                loading: false
                            })

                            //token
                            wx.setStorageSync('token', token);
                            // app.globalData.authToken = token;

                            //存放用户信息
                            wx.setStorageSync('userinfo', userinfo);
                            app.globalData.userInfo = userinfo;

                            // 存放sessionId
                            wx.setStorageSync('ssId', userinfo.WxSessionId);
                            app.globalData.ssId = userinfo.WxSessionId;
                            wx.setStorage({
                                key: "isLoginPage",
                                data: false
                            })
                        })

                        this.setData({
                            toast: {
                                visible: true,
                                text: '登录成功'
                            },
                            loginOk: true
                        })

                        if (this.data.loginOk) {
                            let t = setTimeout(function () {
                                clearTimeout(t)
                                wx.reLaunch({
                                    url: '/pages/index/index',
                                })
                            }, 1500)
                        }

                    } catch (e) {
                        this.setData({
                            loading: false,
                            loginOk: false
                        })
                    }
                }
            })
        }

    },

    toHome() {
        wx.reLaunch({
            url: '/pages/index/index',
        })
    }
})